package test.n00600;


import static utils.Tools.listOf;

public class Problem00670 {
    public static void main(String[] args) {
        // "1001001"
//        println("11", "1");
//        println("1", "111");
//        println("100", "110010");
        println("110010", "10111");
    }

    public static void println(String a, String b) {
        Solution ss = new Solution();
        System.out.println(listOf(a, b) + "," + listOf(ss.addBinary(a, b)));
    }

    public static class Solution {

        public String addBinary(String a, String b) {
            int p1 = a.length() - 1, p2 = b.length() - 1;
            StringBuilder sb = new StringBuilder();
            int t = 0;
            while (p1 >= 0 && p2 >= 0) {
                if (a.charAt(p1) == '0' && b.charAt(p2) == '0') {
                    if (t == 0) {
                        sb.append("0");
                    } else {
                        t = 0;
                        sb.append("1");
                    }
                } else if (a.charAt(p1) == '1' && b.charAt(p2) == '1') {
                    if (t == 0) {
                        sb.append("0");
                    } else {
                        sb.append("1");
                    }
                    t = 1;
                } else {
                    sb.append("1");
                }

                p1--;
                p2--;
            }

            while (p1 >= 0) {
                if (a.charAt(p1) == '1' && t == 1) {
                    t = 1;
                    sb.append("0");
                } else if (a.charAt(p1) == '0' && t == 1) {
                    sb.append("1");
                    t = 0;
                } else {
                    sb.append(a.charAt(p1));
                }
                p1 --;
            }

            while (p2 >= 0) {
                if (b.charAt(p2) == '1' && t == 1) {
                    t = 1;
                    sb.append("0");
                } else if (b.charAt(p2) == '0' && t == 1) {
                    sb.append("1");
                    t = 0;
                } else {
                    sb.append(b.charAt(p2));
                }
                p2 --;
            }

            if (t == 1) {
                sb.append("1");
            }

            return sb.reverse().toString();
        }
    }
}
